<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import MdEditor from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { isDark } from "@/utils/isDark";
import { useArticleStore } from "@/stores/articleStore";
import { articlelogStore } from "@/stores/articlelogStore";
import { ArticleAPI } from "@/api/ArticleAPI";
import axios from "axios";
import { HomeAPI } from "@/api/HomeAPI";
//获取文章的store对象
const articleStore = useArticleStore();
//引入路由
const router = useRouter();
//结构出封面和标签
const { Cover_tags } = storeToRefs(articleStore);
//发送文章标签请求、
articleStore.getArticle_tags();
const direction = ref("rtl");
//是否展示弹框盒子
const drawer = ref(false);
//折叠列表
const add_activeNames = ref(["1"]);
//获取持久储存文章的store对象
const logarticleStore = articlelogStore();
//结构出保存文章信息
const { logArticle } = storeToRefs(logarticleStore);
const onUploadImg = async (files: Blob[], callback: (arg0: any[]) => void) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((rev, rej) => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = async (event) => {
          // event.target.result 即为图片的Base64编码字符串
          let base64_str = event.target!.result;
          //可以在这里写上传逻辑 直接将base64编码的字符串上传（可以尝试传入blob对象，看看后台程序能否解析）
          await HomeAPI.uploadImgFromPaste({
            image: base64_str as string,
          })
            .then((res) => rev(res))
            .catch((error) => rej(error));
        };
      });
    })
  );
  callback(res.map((item: any) => item.url));
};

//文章分类
const category_options = ref([
  { value: 1, label: "前端" },
  { value: 2, label: "后端" },
  { value: 3, label: "项目相关" },
]);

//关闭抽屉函数
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确认要关闭完善文章信息抽屉嘛")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
//完善文章信息的折叠
const handleChange = (val: string[]) => {
  // console.log(val);
};
//更换文章封面
function select_cover(cover_id: number) {
  const img = Cover_tags.value.result.cover_List.filter(
    (item) => item.nid === cover_id
  );
  setTimeout(() => {
    logArticle.value.result.cover_img = img[0].url;
  }, 1);
}
//发布文章
async function add_aarticle() {
  const res = await ArticleAPI.publishArticle(logArticle.value.result);
  if (res.code == 200) {
    ElMessage({
      message: res.status,
      type: "success",
    });
    //清除本地保存
    logarticleStore.$reset();
    // 跳转文章页面
    router.push({
      path: `/article/${res.id}`,
    });
  } else {
    ElMessage.error(res.msg);
  }
}
</script>
<template>
  <main>
    <div class="add_article_actions">
      <el-button type="primary" @click="drawer = true">完善文章信息</el-button>
    </div>
    <el-drawer
      title="完善文章信息"
      v-model="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-collapse v-model="add_activeNames" @change="handleChange">
        <el-collapse-item title="文章标题" name="1">
          <el-input
            v-model.trim="logArticle.result.title"
            ref="active_title"
            placeholder="请输入文章标题"
          />
        </el-collapse-item>
        <el-collapse-item title="文章简介" name="2">
          <el-input
            type="textarea"
            :rows="4"
            resize="none"
            placeholder="请输入文章简介(不填默认截取正文前30个字符)"
            v-model.trim="logArticle.result.abstract"
          >
          </el-input>
        </el-collapse-item>
        <el-collapse-item title="文章分类与标签" name="3">
          <el-select
            v-model="logArticle.result.category_id"
            size="small"
            style="width: 150px"
            placeholder="请选择文章分类"
          >
            <el-option
              v-for="item in category_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-select
            filterable
            allow-create
            default-first-option
            v-model="logArticle.result.tags"
            size="small"
            multiple
            style="margin-left: 200px; margin-top: -25px; width: 150px"
            placeholder="请选择文章标签"
          >
            <el-option
              v-for="item in Cover_tags.result.tags_List"
              :key="item.nid"
              :label="item.title"
              :value="item.nid"
            >
            </el-option>
          </el-select>
        </el-collapse-item>
        <el-collapse-item class="article_cover" title="文章封面" name="4">
          <div class="article_coverch">
            <div class="left">
              <img id="cover_img" :src="logArticle.result.cover_img" alt="" />
            </div>
            <div class="right">
              <el-select
                @change="select_cover(logArticle.result.cover_id)"
                v-model="logArticle.result.cover_id"
                size="small"
                placeholder="请选择文章封面"
              >
                <el-option
                  v-for="item in Cover_tags.result.cover_List"
                  :key="item.nid"
                  :label="item.url.slice(34)"
                  :value="item.nid"
                >
                </el-option>
              </el-select>
            </div>
          </div>
        </el-collapse-item>
        <el-collapse-item title="文章可选设置" name="5">
          <el-switch
            v-model="logArticle.result.recommend"
            active-text="上推荐"
            inactive-text="不上推荐"
          >
          </el-switch>
          <el-switch
            v-model="logArticle.result.pwd_active"
            active-text="加密"
            inactive-text="不加密"
          >
          </el-switch>
          <el-input
            v-show="logArticle.result.pwd_active"
            v-model.trim="logArticle.result.pwd"
            placeholder="请输入文章加密密码"
          ></el-input>
        </el-collapse-item>
      </el-collapse>
      <div class="article_bnt_list">
        <el-button type="success" @click="add_aarticle">发布文章</el-button>
      </div>
    </el-drawer>
    <div>
      <md-editor
        :theme="isDark ? 'dark' : 'light'"
        style="width: 100%; height: 90vh"
        v-model="logArticle.result.content"
        @on-upload-img="onUploadImg"
      />
    </div>
  </main>
</template>

<style scoped lang="scss">
.add_article_actions {
  margin-bottom: 20px;
}
.el-collapse-item {
  padding: 0 20px;
}
.article_cover {
  .article_coverch {
    height: 100px !important;
  }
}
.el-collapse-item__content {
  .left {
    width: 40%;
    margin-bottom: 0px;
    img {
      width: 100%;
    }
  }
  .right {
    position: relative;
    left: 200px;
    top: -70px;
    width: 58%;
    .el-select {
      width: 80%;
    }
  }
  div {
    display: block;
    margin-top: 10px;
  }
}
.el-drawer__body {
  position: relative;
}
.article_bnt_list {
  position: absolute;
  bottom: 20px;
  right: 20px;
}
</style>
